import { gameIdDic } from "../../../config/SvrCfg";
import { IFSess } from "../../../common/interfaces";
import { MsgHandler } from "kilom";
import { MsgId, MsgTos } from "../../../config/Msg";

export default class MsgConnector extends MsgHandler {

    /**
     * 连接服务器
     * @param sess 
     * @param msg
     */
    async connect(sess: IFSess, msg: MsgTos[MsgId.connect]) {
        if (sess.getLocal("user")) return sess.send(MsgId.connect, { code: 2, msg: "已经连接过服务器了" });
        if (!msg.user) return sess.send(MsgId.connect, { code: 2, msg: "账号不存在" });
        if (!gameIdDic[msg.sid]) return sess.send(MsgId.connect, { code: 2, msg: "服务器id不存在" });

        let { err, data: pid } = await this.app.rpc(gameIdDic[msg.sid]).game.login.getPid(msg.user);
        if (err) return sess.send(MsgId.connect, { code: 2, msg: err.msg });

        console.log("连接", err, pid);

        sess.setLocal({ user: msg.user, sid: msg.sid });

        if (pid > 0) {
            sess.bind(pid);
            sess.send(MsgId.connect, { code: 0 });
        } else {
            sess.setLocal({ createRole: true });
            sess.send(MsgId.connect, { code: 1 });
        }
    }

    /**
     * 创角
     * @param sess 
     * @param msg
     */
    async createRole(sess: IFSess, msg: MsgTos[MsgId.createRole]) {
        if (!sess.getLocal("createRole")) return sess.send(MsgId.createRole, { code: 1, msg: "非法操作" });

        let user = sess.getLocal("user");
        let gameId = gameIdDic[sess.getLocal("sid")];
        let { err, data: pid } = await this.app.rpc(gameId).game.login.createRole(user, msg.name, msg.cid);
        if (err) return sess.send(MsgId.createRole, { code: 1, msg: err.msg });

        sess.bind(pid);
        sess.send(MsgId.createRole, { code: 0 });
    }

}